﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Pixysoft.Security
{
    public class IpFilter
    {
        private static volatile IpFilter instance;

        private static object syncRoot = new Object();

        public static IpFilter Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        instance = new IpFilter();
                    }
                }

                return instance;

            }
        }

        /// <summary>
        /// 掩码就是IP的验证模板，例如120.23.255.255
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="mask"></param>
        /// <returns></returns>
        public bool IsPass(string ip, string mask)
        {
            if (!RegexCoder.Instance.IsIP(ip))
                return false;

            if (!RegexCoder.Instance.IsIP(mask))
                return false;

            string[] ips = ip.Split('.');

            string[] masks = mask.Split('.');

            if (masks[0] == "255")
            {
                return true;
            }
            else if (ips[0] != masks[0])
            {
                return false;
            }

            if (masks[1] == "255")
            {
                return true;
            }
            else if (ips[1] != masks[1])
            {
                return false;
            }

            if (masks[2] == "255")
            {
                return true;
            }
            else if (ips[2] != masks[2])
            {
                return false;
            }

            if (masks[3] == "255")
            {
                return true;
            }
            else if (ips[3] != masks[3])
            {
                return false;
            }

            return true;
        }

        private void test()
        {
            Console.Write(IsPass("120.20.208.78", "120.21.208.255"));
        }
    }
}
